//
//  ConsumerLock.m
//  PriceOnline
//
//  Created by Phuong Le on 1/11/13.
//  Copyright (c) 2013 WorkLikeDance. All rights reserved.
//

#import "ConsumerLock.h"

@interface ConsumerLock()
{
    dispatch_semaphore_t consumerSemaphore;
    dispatch_semaphore_t producerSemaphore;
    NSObject* _object;
}

@end

@implementation ConsumerLock

- (id)init
{
    self = [super init];
    if (self)
    {
        consumerSemaphore = dispatch_semaphore_create(0);
        producerSemaphore = dispatch_semaphore_create(0);
        _finished = NO;
    }
    return self;
}

- (void)consume:(void (^)(id))block
{
    BOOL finished = NO;
    while (!finished)
    {
        dispatch_semaphore_wait(consumerSemaphore, DISPATCH_TIME_FOREVER);
        finished = _finished;
        if (!finished)
        {
            block(_object);
            dispatch_semaphore_signal(producerSemaphore);
        }
    }
}

- (void)produce:(id)object
{
    _object = object;
    _finished = NO;
    dispatch_semaphore_signal(consumerSemaphore);
    dispatch_semaphore_wait(producerSemaphore, DISPATCH_TIME_FOREVER);
}

- (void)finish
{
    _finished = YES;
    dispatch_semaphore_signal(consumerSemaphore);
}

- (void)dealloc
{
//    dispatch_release(consumerSemaphore);
//    dispatch_release(producerSemaphore);
}

@end
